/**
 * 群组
 * Created by yanyuan on 2014/12/1.
 */
angular.module('myApp.GroupHandler', ["myApp.CacheServices", "myApp.DataStore", "myApp.GroupModel"])
    .factory("GroupHandler", ["$rootScope", "DataStore", "Group", "LocalCacheService", "$http", "$q",
        function ($rootScope, DataStore, Group, LocalCacheService, $http, $q) {

            var createGroup = function (paramData) {
                $http({
                    method: "POST",
                    url: "group/create.do",
                    data: $.param(paramData),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if (data.error) {
                        swal(data.error);
                        return false;
                    }
                    data.identifier = data.uid;
                    delete data.uid;
                    saveGroup(data);
                    var groups = LocalCacheService.get("groups");
                    if (groups && groups != null) {
                        groups = groups.split(",");
                    } else {
                        groups = [];
                    }
                    groups.push(data.identifier);
                    LocalCacheService.set("groups", groups.join(","));
                    return true;
                }).error(function () {
                    swal("请求服务器失败，请稍后再试！");
                    return false;
                });
            }

            var createGroupPromise = function (paramData) {
                var deferred = $q.defer();
                $http({
                    method: "POST",
                    url: "group/create.do",
                    data: $.param(paramData),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if (data.error) {
                        deferred.reject(data.error);//申明执行失败
                    }
                    data.identifier = data.uid;
                    delete data.uid;
                    saveGroup(data);
                    var groups = LocalCacheService.get("groups");
                    if (groups && groups != null) {
                        groups = groups.split(",");
                    } else {
                        groups = [];
                    }
                    groups.push(data.identifier);
                    LocalCacheService.set("groups", groups.join(","));
                    deferred.resolve(data);
                }).error(function () {
                    deferred.reject("请求服务器失败，请稍后再试！");
                });
                return deferred.promise; //返回执行状态
            }

            var queryGroup = function(paramData){
                $http({
                    method: "POST",
                    url: "group/query.do",
                    data: $.param(paramData),
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    data.identifier = data.uid;
                    delete data.uid;
                    DataStore.saveGroup(data);
                    return data;
                }).error(function () {
                    swal("请求服务器获取群信息失败！！");
                    return false;
                });
            }

            //paramData : {groupUid : groupIdentifier}
            var queryGroupPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method: "POST",
                    url: "group/query.do",
                    data: $.param(paramData),
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);//申明执行失败
                    }
                    data.identifier = data.uid;
                    delete data.uid;
                    deferred.resolve(data);//声明执行成功，且返回数据
                }).error(function () {
                    deferred.reject("请求服务器获取群信息失败！");
                });
                return deferred.promise; //返回执行状态
            }

            var getGroupByIdentifier = function(identifier){
                return DataStore.getGroupMap()[identifier];
            }

            var groupIsExist = function(identifier){
                return getGroupByIdentifier(identifier);
            }

            var saveGroup = function(group){
                DataStore.saveGroup(group);
            }

            var addContactPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method: "POST",
                    url: "group/addContact.do",
                    data: $.param(paramData),
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function (data) {
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);//申明执行失败
                    }
                    deferred.resolve(data);//声明执行成功，且返回数据
                }).error(function () {
                    deferred.reject("请求服务器失败！");
                });
                return deferred.promise; //返回执行状态
            }

            var updateGroupPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method : "POST",
                    url : "group/update.do",
                    data : $.param(paramData),
                    headers :  { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function(data){
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);
                    }
                    deferred.resolve(data);
                }).error(function(){
                    deferred.reject("请求服务器失败！");
                });
                return deferred.promise;
            }

            var exitGroupPromise = function(paramData){
                var deferred = $q.defer();
                $http({
                    method : "POST",
                    url : "group/exit.do",
                    data : $.param(paramData),
                    headers :  { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function(data){
                    if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                        util.tokenExpire();
                        return;
                    }
                    if(data.error){
                        deferred.reject(data.error);
                    }
                    deferred.resolve(data);
                }).error(function(){
                    deferred.reject("请求服务器失败！");
                });
                return deferred.promise;
            }

            var getGroupMap = function(){
                return DataStore.getGroupMap();
            }

            var getGroups = function(){
                return DataStore.getGroups();
            }

            var getDeptGroupIdentifiers = function(){//获取部门群组
                return DataStore.getDeptGroupIdentifiers();
            }

            var getMyDeptGroups = function(){
                var myDeptGroups = [];
                angular.forEach(DataStore.getGroups(), function(group){
                   if(getDeptGroupIdentifiers().contains(group.identifier)){
                       myDeptGroups.push(group);
                   }
                });
                return myDeptGroups;
            }

            var refreshGroup = function(){
                $rootScope.groupMap = getGroupMap();
                $rootScope.groups = getGroups();
            }

            return {
                createGroup: createGroup,
                createGroupPromise : createGroupPromise,
                queryGroup : queryGroup,
                queryGroupPromise : queryGroupPromise,
                getGroupByIdentifier : getGroupByIdentifier,
                groupIsExist : groupIsExist,
                saveGroup : saveGroup,
                addContactPromise : addContactPromise,
                updateGroupPromise : updateGroupPromise,
                exitGroupPromise : exitGroupPromise,
                getGroupMap : getGroupMap,
                getGroups : getGroups,
                getDeptGroupIdentifiers : getDeptGroupIdentifiers,
                getMyDeptGroups : getMyDeptGroups,
                refreshGroup : refreshGroup
            }
        }]);